package com.hnkywl.sts.action.cggl;

import com.hnkywl.sts.service.cggl.CgdUploadService;
import com.hnkywl.sts.util.POIUtil;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-4-15
 * Time: 下午2:17
 * To change this template use File | Settings | File Templates.
 */
@Namespaces({@Namespace("/cggl/cgdgl")})
public class CgdUploadAction extends SimpleActionSupport {
    private CgdUploadService cgdUploadService;
    private File upload;

    @Action("cgd_upload")
    public String bgjhmxUpload() {
        return SUCCESS;
    }

    /**
     * 外部入库信息导入
     */
    @Action("cgd_import")
    public void bgjhmxImport() {
        Integer row = 0;
        try {
            Workbook book = Workbook.getWorkbook(upload);
            //  获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            //获取总行数
            int rows = sheet.getRows();
            String check = "0";
            List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
            for (int i = 1; i < rows; i++) { //从第2行开始导入
                row = i + 1;
                Map<String, String> map = new HashMap<String, String>();
                if (checkResult(sheet.getCell(0, i), false)) {
                    String sellSubNo = sheet.getCell(0, i).getContents().toString();//销售合同子项号
                    map.put("sellSubNo", sellSubNo);
                } else {
                    check = "1";
                    break;
                }
                if (checkResult(sheet.getCell(1, i), false)) {
                    String carNo = sheet.getCell(1, i).getContents().toString();//车号
                    map.put("carNo", carNo);
                } else {
                    check = "1";
                    break;
                }
                if (checkResult(sheet.getCell(2, i), false)) {
                    String bindNo = sheet.getCell(2, i).getContents().toString();//捆包号
                    map.put("bindNo", bindNo);
                } else {
                    check = "1";
                    break;
                }
                if (checkResult(sheet.getCell(3, i), false)) {
                    String number = sheet.getCell(3, i).getContents().toString();//件数
                    map.put("number", number);
                } else {
                    check = "1";
                    break;
                }
                if (checkResult(sheet.getCell(4, i), false)) {
                    String weight = sheet.getCell(4, i).getContents().toString();//重量
                    map.put("weight", weight);
                } else {
                    check = "1";
                    break;
                }
                if (checkResultDate(sheet.getCell(5, i))) {
                    String fDate = sheet.getCell(5, i).getContents().toString();//出厂日期
                    map.put("fDate", fDate);
                } else {
                    check = "1";
                    break;
                }
                if (checkResult(sheet.getCell(6, i), false)) {
                    String serial = sheet.getCell(6, i).getContents().toString();//仓储资源唯一号
                    map.put("resource_serial_number_1", serial);
                } else {
                    check = "1";
                    break;
                }
                listMap.add(map);
            }
            if (StringUtils.equals(check, "0")) {
                String result = cgdUploadService.saveUploadCgd(listMap);
                renderText("{\"statusCode\":\"200\", \"message\":\"批量导入成功！" + result + "\"}");
            } else if (StringUtils.equals(check, "1")) {
                String str = "第（" + row + "）行错误，";
                renderText("{\"statusCode\":\"300\", \"message\":\"" + str + "可能为空，可能不是数字，日期应该为：2015-08-08格式！" + "\"}");
//            } else {
//                String str = "第（" + row + "）行错误，";
//                renderText("{\"statusCode\":\"300\", \"message\":\"" + str + "运营系统没有品名：[" + name + "]材质为：[" + cz + "]规格：[" + ggxh + "] \"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"数据异常：" + e.getMessage().replace("\"", " ") + "\"}");
        }
    }

    /**
     * 判断格式是否正确
     *
     * @param cell
     * @param bool
     * @return
     */
    private boolean checkResult(Cell cell, boolean bool) {
        if (null != cell && null != cell.getContents() && org.apache.commons.lang3.StringUtils.isNotBlank(cell.getContents().toString())) {
            if (bool) {
                try {
                    Double dd = Double.valueOf(cell.getContents().toString());
                    if (dd <= 0) {
                        return false;
                    } else {
                        return true;
                    }
                } catch (Exception e) {

                }
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断日期是否正确
     *
     * @param cell
     * @return
     */
    private boolean checkResultDate(Cell cell) {
        if (null != cell && null != cell.getContents() && org.apache.commons.lang3.StringUtils.isNotBlank(cell.getContents().toString())) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdf.parse(cell.getContents().toString());
                return true;
            } catch (Exception e) {

            }
        }
        return false;
    }

    /** 外部入库导入模板 */
    @Action("cgd_export")
    public String bgjhmx_export() {
        //第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheet1");
        POIUtil poiUtil = new POIUtil(wb);
        //设置列宽
        sheet.setDefaultRowHeightInPoints(15);
        sheet.setDefaultColumnWidth((short) 12);
        sheet.setColumnWidth((short) 0, (short) (20 * 200));
        sheet.setColumnWidth((short) 1, (short) (20 * 200));
        sheet.setColumnWidth((short) 2, (short) (20 * 200));
        sheet.setColumnWidth((short) 3, (short) (20 * 200));
        sheet.setColumnWidth((short) 4, (short) (20 * 200));
        sheet.setColumnWidth((short) 5, (short) (20 * 200));
        sheet.setColumnWidth((short) 6, (short) (20 * 200));
        //第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        row.setHeightInPoints(36);
        //第四步，创建单元格，并设置值表头  设置表头居中
//        HSSFCellStyle titleStyle = poiUtil.createTitleHSSFCellStyle(wb);
//        HSSFCell titleCell = row.createCell((short) 0);
//        titleCell.setCellStyle(titleStyle);
//        titleCell.setEncoding(HSSFCell.ENCODING_UTF_16);
//        titleCell.setCellValue("攀钢物资明细导入模板");
//        sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 2));
        //生成第一行数据...表头
        HSSFCellStyle headerStyle = poiUtil.createHeader3HSSFCellStyle(wb);
//        poiUtil.fillRow(sheet, headerStyle, 0, "销售订单子项号", "车号", "捆包号", "件数", "重量", "出厂日期", "仓储资源唯一号");
        poiUtil.fillRow(sheet, headerStyle, 0, "合同子项号", "车号", "捆包号", "件数", "重量", "出厂日期", "仓储资源唯一号");
        //生成从第二行开始的企业机构数据
        try {
            response.setContentType("application/x-download");
            String filedisplay = new String(("外部入库导入模板.xls").getBytes("gb2312"), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
            wb.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            renderText("位置异常，导出失败" + e.getMessage());
        }
        return null;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public void setCgdUploadService(CgdUploadService cgdUploadService) {
        this.cgdUploadService = cgdUploadService;
    }
}
